//
//  EstimateLable.m
//  BrushFace
//
//  Created by Harry on 16/2/26.
//  Copyright © 2016年 Zzz. All rights reserved.
//

#import "EstimateLable.h"

@interface EstimateLable ()
@property(nonatomic,strong)NSTimer *timer;
@property (assign, nonatomic) NSInteger remainsecond;
@end
@implementation EstimateLable

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setTextAlignment:NSTextAlignmentCenter];
        [self setTextColor:[UIColor whiteColor]];
        [self setFont:[UIFont systemFontOfSize:13]];
        self.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.2];
        
    }
    return self;
}
-(void)timerStart
{
    if(!_timer)
    {
        _timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeChanged) userInfo:nil repeats:YES];
        
        //这儿写可能会有问题  暂时为了实现效果
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        [_timer fire];
        
        
    }
}
-(void)timeChanged
{
    
    _remainsecond = _remainsecond-1;
    self.text = [self timeFormatted:_remainsecond];
    
    if (_remainsecond <= 0)
    {
        
        self.text = @"『好友可能在忙，邀请更多好友，来帮您吧』";
        
        [self timerStop];
    }
}
-(void)timerStop
{
    if (_timer) {
        
        
        //如果定时器在运行
        if ([self.timer isValid]) {
            
            NSLog(@"单击停止按钮，取消定时器！！");
            
            [self.timer invalidate];
            
            _timer=nil;
            
        }
        
    }
}
- (NSString *)timeFormatted:(NSInteger)totalSeconds
{
    
    NSInteger seconds = totalSeconds % 60;
    NSInteger minutes = (totalSeconds / 60) % 60;
    NSInteger hours = totalSeconds / 3600;
    
    return [NSString stringWithFormat:@"预计:%02ld:%02ld:%02ld 后满额",(long)hours,(long)minutes,(long)seconds];
    
    
}

-(void)setExpiredate:(NSString *)expiredate
{
    _expiredate = expiredate;
//    NSTimeInterval time =[[NSDate date] timeIntervalSince1970];
//    _remainsecond = [_expiredate integerValue]- (NSInteger)time ;
    _remainsecond = [_expiredate integerValue];
    if (_remainsecond>0)
    {
        [self timerStart];
    }
    else
    {
        self.text = @"『好友可能在忙，邀请更多好友，来帮您吧』";
    }
    
}
@end
